package cn.ecpay.unionpay.settle.dao;

import cn.ecpay.unionpay.settle.entity.db.TPvFundSettleSingle;
import cn.ecpay.unionpay.settle.entity.db.TPvReturnMoney;
import org.rex.DB;
import org.rex.db.Ps;
import org.rex.db.exception.DBException;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 回款
 * Created by zhaoyanzeng on 2018/12/10.
 */
@Repository
public class ReturnMoneyDao {

    /**
     * 保存回款
     *
     * @param returnMoney
     * @throws DBException
     */
    public void insert(TPvReturnMoney returnMoney) throws DBException {
        String sql = "INSERT INTO T_PV_RETURN_MONEY" +
                "(ID,TXN_NO,TXN_TYPE,ACQ_INS_CODE,TXN_DATE,SEND_TIME,INS_SEQ,PAYER_ACCT_NO,PAYER_ACCT_NAME,CURRENCY_CODE,TXN_AMT,REMARK,RESP_CODE," +
                "RESP_MSG,RESP_VALIDATE,CREATE_TIME,NOTIFY_RESP_CODE,NOTIFY_RESP_MSG,IS_NOTIFY,NOTIFY_TIME,NOTIFY_VALIDATE)" +
                " VALUES " +
                "(#{id},#{txnNo},#{txnType},#{acqInsCode},#{txnDate},#{sendTime},#{insSeq},#{payerAcctNo},#{payerAcctName},#{currencyCode},#{txnAmt},#{remark},#{respCode}," +
                "#{respMsg},#{respValidate},#{createTime},#{notifyRespCode},#{notifyRespMsg},#{isNotify},#{notifyTime},#{notifyValidate})" ;
        DB.update(sql, returnMoney);
    }

    /**
     * 更新回款通知
     *
     * @param returnMoney
     * @throws DBException
     */
    public void update(TPvReturnMoney returnMoney) throws DBException {
        String sql = "UPDATE T_PV_RETURN_MONEY SET NOTIFY_RESP_CODE=#{notifyRespCode},NOTIFY_RESP_MSG=#{notifyRespMsg}," +
                "IS_NOTIFY=#{isNotify},NOTIFY_TIME=#{notifyTime},NOTIFY_VALIDATE=#{notifyValidate} WHERE TXN_NO=#{txnNo}";
        DB.update(sql, returnMoney);
    }

    /**
     * 根据id查询交易信息
     *
     * @param id
     * @return
     */
    public TPvReturnMoney find(String id) throws DBException {
        String sql = "SELECT * FROM T_PV_RETURN_MONEY WHERE ID=?";
        return DB.get(sql,new Object[]{id},TPvReturnMoney.class);
    }

    /**
     * 根据交易流水号查询交易信息
     *
     * @param txnNo 流水号
     * @return
     */
    public TPvReturnMoney findMsgByTxnNo(String txnNo) throws DBException {
        String sql ="SELECT * FROM T_PV_RETURN_MONEY WHERE TXN_NO=?";
        return DB.get(sql, new Object[]{txnNo}, TPvReturnMoney.class);
    }

    /**
     * 当天交易流水号不能重复
     * @param txnNo
     * @param txnDate
     * @return
     * @throws DBException
     */
    public boolean isExistTxn(String txnNo, String txnDate) throws DBException {
        Ps ps = new Ps();
        String sql = "SELECT * FROM T_PV_RETURN_MONEY WHERE TXN_NO=? and TXN_DATE =?";
        ps.add(txnNo);
        ps.add(txnDate);
        List<TPvFundSettleSingle> list = DB.getList(sql,ps,TPvFundSettleSingle.class);
        if(list!= null && list.size()>0){
            return true;
        }
        return false;
    }
}
